package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.common.JwtUtils;
import com.itheima.common.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class DemoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("--------DemoInterceptor preHandle----------------");
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            Result<?> error = Result.error("NOT_LOGIN");
            response.setContentType("application/json;charset=utf-8");
            String json = JSON.toJSONString(error);
            response.getWriter().write(json);
            return false;
        }
        try {
            Claims claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            Result<?> error = Result.error("NOT_LOGIN");
            response.setContentType("application/json;charset=utf-8");
            String json = JSON.toJSONString(error);
            response.getWriter().write(json);
            return false;
        }

        return true;
    }
}
